package com.example.demo.utils;


import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class HttpClientUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    private String ipApiKey;
    private String ipApiUrl;

    @Autowired
    public HttpClientUtils(@Value("${ip.api.url}") String ipApiUrl, @Value("${ip.api.key}") String ipApiKey) {
        this.ipApiUrl = ipApiUrl;
        this.ipApiKey = ipApiKey;
    }

    public HashMap<String, Object> getIp() {
        HashMap<String, Object> resultMap = new HashMap<>();
        int retryCount = 0;
        final int maxRetries = 3;
        while (retryCount < maxRetries) {
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                String fullUrl = ipApiUrl + "?key=" + ipApiKey;
                HttpGet httpGet = new HttpGet(fullUrl);
//                发送请求
                HttpResponse httpResponse = httpClient.execute(httpGet);
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    String result = EntityUtils.toString(httpResponse.getEntity());
//                    解析json数据
                    String jsonResponse = String.valueOf(new JSONObject(result));
                    JSONObject jsonObject = new JSONObject(jsonResponse);
                    resultMap.put("province", jsonObject.getString("province"));
                    resultMap.put("city", jsonObject.getString("city"));
                    resultMap.put("adcode", jsonObject.getString("adcode"));
                    return resultMap;
                } else {
                    System.out.println("Failed to get IP. Status code: " + httpResponse.getStatusLine().getStatusCode());
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                logger.error("Error occurred while calling IP API", e);
            }
            retryCount++;
        }
        logger.error("Failed to get IP after {} retries", maxRetries);
        return null;
    }

    //    通用的get网络请求函数
    public static String sendGetRequest(String url) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(httpResponse.getEntity());
                String jsonResponse = String.valueOf(new JSONObject(result));
                JSONObject jsonObject = new JSONObject(jsonResponse);
                return jsonObject.getString("data");
            } else {
                logger.error("Failed to send GET request. Status code: {}", httpResponse.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            logger.error("Error occurred while sending GET request to URL: {}", url, e);
        }
        return null;
    }
}
